
<template>
  <div>
    <page :asideShow="asideShow" :dropDown="false">
      <div slot="toolbar">
        <el-form :rules="formRules" :model="dataForm" ref="dataForm" label-width="80px">
          <div class="row">
            <div class="col">
              <el-form-item prop="GID" label="可见机构" style="margin-bottom: 10px">
                <el-cascader
                  v-model="dataForm.GID"
                  :options="organizeMix"
                  :props="{
                    multiple: false,
                    value: 'GID',
                    label: 'name',
                    children: 'children',
                    checkStrictly: true,
                    emitPath: false,
                    disabled: 'disableds'
                  }"
                  :show-all-levels="false"
                  clearable
                ></el-cascader>
              </el-form-item>
              <el-form-item prop="title" label="公告主题" style="margin-bottom: 10px">
                <el-input v-model="dataForm.title" auto-complete="off"></el-input>
              </el-form-item>
              <el-form-item label="公告海报" prop="poster">
                <el-upload
                  ref="uploadImg"
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :before-upload="beforeRead"
                  :on-success="handleAvatarSuccess"
                >
                  <img v-if="this.dataForm.poster" :src="getItemPhoto(dataForm.poster)" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>

              <el-form-item label="公告序号">
                <el-input-number v-model="dataForm.num" :min="1" :max="1000" label="描述文字"></el-input-number>
              </el-form-item>
            </div>
            <el-form-item label="公告内容" prop="content" style="margin-bottom: 28px">
              <vue-tinymce v-model="dataForm.content" :setting="setting" />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer cen">
        <el-button @click.native="closedialog">取消</el-button>
        <el-button type="primary" @click.native="submitForm">确认</el-button>
      </div>
    </page>
  </div>
</template>

<script>
import fileUtils from "@/utils/fileUtils.js";
export default {
  props: {},
  data() {
    return {
      dataForm: {
        title: "",
        content: "",
        GID: "",
        num: 1,
        poster: ""
      },
      formRules: {
        title: [{ required: true, message: "标题必填", trigger: "blur" }],
        GID: [{ required: true, message: "机构必选", trigger: "blur" }],
        content: [{ required: true, message: "内容必填", trigger: "blur" }],
        // poster: [{ required: true, message: "海报必填", trigger: "blur" }],
        num: [
          {
            required: true,
            type: "number",
            message: "序号必填且为数字",
            trigger: "blur"
          }
        ]
      },
      getCommunity: [],
      asideShow: false,
      setting: {
        menubar: false,
        toolbar:
          "undo redo importword | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |",
        toolbar_drawer: "sliding",
        quickbars_selection_toolbar:
          "removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor | quickimage quicktable",
        plugins: "link image media table lists fullscreen quickbars importword",
        images_upload_handler: this.images_upload_handler,
        language: "zh_CN", //本地化设置
        width: 414,
        height: 736
        // skin: "oxide-dark"
      }
    };
  },
  async created() {
    const { params, query } = this.$route;
    const { dataForm } = query;
    if (dataForm) this.dataForm = dataForm;
    if (!this.dataForm.poster) {
      this.dataForm.poster = "";
    }

    this.organizeMix = await this.getOrganizeMix();
  },
  methods: {
    // 关闭
    closedialog() {
      this.$router.push("/commadmin/Notices");
    },

    // 表单提交
    submitForm() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
            this.editLoading = true;
            let params = Object.assign({}, this.dataForm);
            params.status = 1;
            this.$api.wxNotic.add_notice({ where: params }).then((res) => {
              this.editLoading = false;
              if (res.code == 0) {
                this.$message({
                  message: "操作成功",
                  type: "success"
                });
                this.closedialog();
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  type: "error"
                });
              }
            });
          });
        }
      });
    },
    async images_upload_handler(blobInfo, succFun, failFun) {
      var param = blobInfo.blob(); //转化为易于理解的file对象
      const imgup = await this.getBase64(param).then();
      const paramd = {
        img: imgup
      };
      let rsid = await this.$api.imgAdd.addimgPer(paramd).then((res) => {
        return res;
      });
      if (!rsid.id.length) failFun("isErr");
      let url = this.getItemPhoto(rsid.id);
      succFun(url);
    },
    getItemPhoto(id) {
      var url = this.global.baseUrlImage + "avatar/" + id;
      return url;
    },
    //图片处理
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },

    handleAvatarSuccess(res, file) {
      this.addImgUrl = URL.createObjectURL(file.raw);
    },
    beforeRead(file) {
      let that = this;
      return new Promise((resolve) => {
        fileUtils.getOrientation(file).then((orient) => {
          let reader = new FileReader();
          let img = new Image();
          reader.onload = (e) => {
            img.src = e.target.result;
            img.onload = async function () {
              let width = 600,
                height = 600 * (img.height / img.width);
              const data = await fileUtils.rotateImage(img, width, height, orient);
              const newFile = await fileUtils.dataURLtoFile(data, file.name);
              resolve(that.upLoad(newFile));
            };
          };
          reader.readAsDataURL(file);
        });
      });
    },
    //图片处理
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 编辑添加图片
    async upLoad(param) {
      var imgup = "";
      await this.getBase64(param).then((res) => {
        imgup = res;
      });
      var paramd = {
        img: imgup
      };
      this.$api.imgAdd.addimgPer(paramd).then((res) => {
        this.dataForm.poster = res.id;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.cen {
  text-align: center;
}
.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.mr20 {
  margin-right: 20px;
}
.col {
  display: flex;
  flex-direction: column;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
}
</style>
